package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //api/order/auth/trade  网关中设置了这个路径必须登录
    @GetMapping("auth/trade")
    public Result authTrade(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //获取送货地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //获取送货清单
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //循环遍历给订单明细赋值
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            //返回数据
            return orderDetail;
        }).collect(Collectors.toList());

        //计算总价格
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();
        //存储数据
        map.put("userAddressList", userAddressList);
        //订单页面需要换---->换成没有优惠券的页面
        map.put("detailArrayList", orderDetailList);
        map.put("totalNum", orderDetailList.size());
        map.put("totalAmount", orderInfo.getTotalAmount());
        //保存一个流水号
        map.put("tradeNo",orderService.getTradeNo(userId));

        //第二种：
        //        List<OrderDetail> detailArrayList = new ArrayList<>();
        //        cartCheckedList.stream().forEach(cartInfo -> {
        //            OrderDetail orderDetail = new OrderDetail();
        //            orderDetail.setSkuId(cartInfo.getSkuId());
        //            orderDetail.setSkuName(cartInfo.getSkuName());
        //            orderDetail.setImgUrl(cartInfo.getImgUrl());
        //            orderDetail.setSkuNum(cartInfo.getSkuNum());
        //            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
        //            // 添加到集合
        //            detailArrayList.add(orderDetail);
        //        });
        //返回
        return Result.ok(map);
    }

    //提交订单
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //获取到页面的流水号
        String tradeNo = request.getParameter("tradeNo");
        //调用比较方法
        Boolean result = orderService.checkTradeNo(tradeNo, userId);
        if(!result){
            return Result.fail().message("不能回退无刷新重复提交订单");
        }
        //删除缓存流水号
        orderService.delTradeNo(userId);

        //        //验证库存
        //        for (OrderDetail orderDetail : orderInfo.getOrderDetailList()) {
        //            Boolean res = orderService.checkStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
        //            //校验库存
        //            if(!res){
        //                return Result.fail().message(orderDetail.getSkuNum()+"没有足够的库存");
        //            }
        //            //校验价格
        //            BigDecimal orderPrice = orderDetail.getOrderPrice();
        //            //实时价格
        //            BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
        //            if(orderPrice.compareTo(skuPrice)!=0){
        //                //设置最新的价格
        //                List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //                //写入缓存
        //                cartCheckedList.forEach(cartInfo -> {
        //                    this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX+userId+RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(),cartInfo );
        //                });
        //                return Result.fail().message(orderDetail.getSkuNum()+"价格有变动");
        //            }
        //        }

        //多线程优化：
        //声明异步编排集合
        List<String> errorList = new ArrayList<>();
        List<CompletableFuture> futureList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (CollectionUtils.isEmpty(orderDetailList)){
            //循环遍历当前的订单明细
            for (OrderDetail orderDetail : orderDetailList) {
                //验证库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    Boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    //校验库存
                    if (!res) {
                        errorList.add(orderDetail.getSkuNum() + "没有足够的库存");
                    }
                }, threadPoolExecutor);
                //将这个对象添加到集合
                futureList.add(stockCompletableFuture);

                //验证价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //实时价格
                    BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //设置最新的价格
                        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
                        //写入缓存
                        cartCheckedList.forEach(cartInfo -> {
                            this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                        });
                        errorList.add(orderDetail.getSkuNum() + "价格有变动");
                    }
                }, threadPoolExecutor);
                //添加到集合
                futureList.add(priceCompletableFuture);
            }
        }

        //有个任务组合
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();

        //验证是否有错误
        if (errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }

        orderInfo.setUserId(Long.parseLong(userId));
        //调用服务层方法
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //默认返回
        return Result.ok(orderId);
    }

    //查看我的订单
    @GetMapping("auth/{page}/{limit}")
    public Result orderList(@PathVariable Long page,
                            @PathVariable Long limit,
                            HttpServletRequest request){
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> orderInfoPage = new Page<>(page,limit);
        //获取到数据
        IPage<OrderInfo> infoPage = orderService.getPage(orderInfoPage, userId);
        //返回
        return Result.ok(infoPage);
    }
}
